Keep these minimal snippets handy for assignments.

  • The key takeaway is to start from a reliable template, then adapt it to the specific problem requirements.
  • BFS uses a queue (first-in, first-out) to explore level by level.
  • DFS uses a stack (last-in, first-out) to explore as deeply as possible along each branch.
  • In Python, collections.deque is highly efficient for both. Use popleft() for a queue (BFS) and pop() for a stack (DFS).
  • In C++, use std::queue for BFS and std::stack for DFS. In C, you'd typically implement these data structures using a dynamically-sized array or a linked list.